﻿using System.Web.Mvc;
using Xoohoo.Models;

namespace Xoohoo.ActionFilters.Authorization
{
    /// <summary>
    /// 防止CSRF攻击
    /// </summary>
    public class AntiForgeryAuthorizationFilter : IAuthorizationFilter
    {
        private readonly Site _site;

        public AntiForgeryAuthorizationFilter(Site site)
        {
            this._site = site;
        }

        #region IAuthorizationFilter Members

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!(filterContext.RouteData.Values["validateAntiForgeryToken"] is bool
                && (bool)filterContext.RouteData.Values["validateAntiForgeryToken"]
                && filterContext.HttpContext.Request.HttpMethod == "POST"
                && filterContext.RequestContext.HttpContext.Request.IsAuthenticated))
            {
                return;
            }

            ValidateAntiForgeryTokenAttribute validator = new ValidateAntiForgeryTokenAttribute { Salt = _site.SiteID.ToString() };

            validator.OnAuthorization(filterContext);
        }

        #endregion
    }
}
